import tkinter as tk
from tkinter import messagebox
import time

# 初始化变量
talk_text = ""
u_name = ''
fruit = ''
order = False
# 顾客愿望单（有待进化的方向）
users = {
    1: {'颜色': ['绿色', '条纹'], '重量': [2000, 5000], '口感': ['沙', '甜']}
}
# 水果商店:在售水果（现有的器官：感受器、效应器）
shop = [
    {'香蕉': {'价格': [3], '颜色': ['黄色'], '重量': [100, 200], '口感': ['甜', '面'], '库存': 50}},
    {'苹果': {'价格': [5], '颜色': ['红色', '绿色'], '重量': [100, 300], '口感': ['甜', '脆'], '库存': 50}},
    {'梨': {'价格': [2], '颜色': ['黄色', '绿色'], '重量': [200, 300], '口感': ['甜', '脆'], '库存': 50}}
]
# 水果批发市场:在售水果（潜在的器官）
fruits = [
    {'香蕉': {'价格': [2], '颜色': ['黄色'], '重量': [100, 200], '口感': ['甜', '面'], '库存': 1000}},
    {'苹果': {'价格': [3], '颜色': ['红色', '绿色'], '重量': [100, 300], '口感': ['甜', '脆'], '库存': 1000}},
    {'梨': {'价格': [1], '颜色': ['黄色', '绿色'], '重量': [200, 300], '口感': ['甜', '脆'], '库存': 1000}},
    {'葡萄': {'价格': [2], '颜色': ['紫色', '绿色', '黑色'], '重量': [10, 20], '口感': ['甜', '酸'], '库存': 1000}},
    {'本地西瓜': {'价格': [1], '颜色': ['绿色', '条纹'], '重量': [2000, 5000], '口感': ['甜', '沙'], '库存': 1000}},
    {'进口西瓜': {'价格': [8], '颜色': ['绿色', '条纹'], '重量': [2000, 5000], '口感': ['甜'], '库存': 100}},
    {'红富士': {'价格': [4], '颜色': ['红色'], '重量': [200, 300], '口感': ['甜', '脆'], '库存': 1000}}
]

# 核心算法
def main():
    global users, fruits
    # 有愿望单
    if len(users) > 0:
        for us in users:
            # 用户需求
            que = users[us]
            names = []
            max = 0
            for key in que:
                mun = 0
                # 遍历批发市场
                for f_name in fruits:
                    f_data = list(f_name.values())[0]
                    u_data = que[key]
                    u_len = len(u_data)
                    u_mun = 0
                    u_size = 0
                
                    # 如果水名字相等，积5分
                    if list(f_name.keys())[0] == key:
                        u_size += 5
                    # 重量特征
                    elif key == '重量':
                        u_min = que[key][0]
                        u_max = que[key][1]
                        f_min = f_data[key][0]
                        f_max = f_data[key][1]
                        if u_min >= f_min and u_max <= f_max:
                            u_size = 1
                    else:
                    # 其它特征
                        for i in range(u_len):
                            if u_data[i] in f_data[key]:
                                u_mun += 1
                        u_size = u_mun / u_len
                    mun += u_size
                # 记录分数最高的水果
                if mun == max:
                    names.append(list(f_name.keys())[0])
                elif mun > max:
                    max = mun
                    names = [list(f_name.keys())[0]]
            name = names[0]
            nm_min = 0
            # 选择价格最低的水果
            for ff in fruits:
                if names[0] in ff:
                    # 获取价格
                    nm_min = ff[names[0]]['价格'][0]
            # 遍历其它水果
            for nm in names:
                # 获取当前水果价格
                nm_p = [x[nm]['价格'][0] for x in fruits if nm in x][0]
                if nm_p < nm_min:
                    nm_min = nm_p
                    name = nm
            print(f'用户{us}想要购买的可能是{name}')
    else:
        messagebox.showinfo("提示", "没有未满足的客户需求！")
    print('思考是否要进货')

# 顾客询问
def ask():
    global talk_text
    str = entry.get()
    str = str.strip()
    if str:
        talk_text += f"顾客: {str}\n"
        talk.config(state=tk.NORMAL)
        talk.insert(tk.END, f"顾客: {str}\n")
        talk.config(state=tk.DISABLED)
        answer(str)

# 机器人回答
def answer(txt):
    global talk_text, fruit
    str = '您想要什么水果？'  # 默认回答
    # 关于水果名称
    import re
    name_reg = re.compile(r'有(.{1,4})吗|？')
    f_name = name_reg.search(txt)
    # 关于水果价格
    price_reg = re.compile(r'多少钱|多少钱？|怎么卖的')
    f_price = price_reg.search(txt)
    # 关于水果口感
    ask_reg = re.compile(r'(.*)不(.*)')
    f_ask = ask_reg.search(txt)
    if f_name:
        str = my_shop(f_name.group(1))
    elif f_price:
        # 价格
        if fruit:
            str = str(fruit['价格'][0]) + '元钱一斤'
    elif f_ask:
        if fruit and f_ask.group(1) in fruit['口感']:
            str = f_ask.group(1)
        else:
            str = '不' + f_ask.group(1)
    else:
        # 默认当做水果名处理
        str = my_shop(txt)
    talk_text += f"机器人: {str}\n"
    talk.config(state=tk.NORMAL)
    talk.insert(tk.END, f"机器人: {str}\n")
    talk.config(state=tk.DISABLED)

# 获得水果名称和库存
def my_shop(s):
    global fruit
    str = ''
    fruit = ''
    for i in shop:
        if s in i:
            fruit = i[s]
            if fruit['库存'] > 0:
                str = '有'
            else:
                str = '没有'
            break
    if not fruit:
        # 显示未知水果调查问卷（准备）
        questionnaire.pack()
        new_name_entry.insert(0, s)
    return str
# 购买
def buy():
    global order
    order = True
    print('下单成功，等待发货！')

# 当前顾客离开超市
def out():
    global u_name
    # 可编辑才能删除
    talk.config(state=tk.NORMAL)
    # 重置聊天区，接待下一位顾客
    talk.delete('1.0', tk.END)
    entry.delete(0, tk.END)
    u_name = time.time()
    print(f'顾客{u_name}离开')

# 提交调查问卷（了解达成目的的具体属性要求）
def new_submit():
    global users
    js = {}
    js['名称'] = [new_name_entry.get()]
    js['颜色'] = [new_color_entry.get()]
    try:
        min_weight = int(min_weight_entry.get())
        max_weight = int(max_weight_entry.get())
        js['重量'] = [min_weight, max_weight]
    except ValueError:
        messagebox.showerror("错误", "重量必须为整数！")
        return
    js['形状'] = [new_shape_entry.get()]
    js['口感'] = [new_flavor_entry.get()]
    users[len(users) + 1] = js
    questionnaire.pack_forget()

# 创建主窗口
root = tk.Tk()
root.title("水果超市进货过程")

# 交流区
talk = tk.Text(root, state=tk.DISABLED, width=50, height=10)
talk.pack()

# 输入框
entry = tk.Entry(root, width=50)
entry.pack()

# 按钮
button_frame = tk.Frame(root)
button_frame.pack(fill=tk.X)
main_button = tk.Button(button_frame, text="判断是否准备进新货", command=main)
main_button.pack(side=tk.LEFT)
ask_button = tk.Button(button_frame, text="询问", command=ask)
ask_button.pack(side=tk.RIGHT)
buy_button = tk.Button(button_frame, text="购买", command=buy)
buy_button.pack(side=tk.RIGHT)
out_button = tk.Button(button_frame, text="离开", command=out)
out_button.pack(side=tk.RIGHT)

# 调查问卷
questionnaire = tk.Frame(root)

table = tk.Frame(questionnaire)
table.pack()

tk.Label(table, text="您能详细描述下这个水果吗？").grid(row=0, column=0, columnspan=3)
tk.Label(table, text="名称：").grid(row=1, column=0)
new_name_entry = tk.Entry(table)
new_name_entry.grid(row=1, column=1)

tk.Label(table, text="颜色：").grid(row=2, column=0)
new_color_entry = tk.Entry(table)
new_color_entry.grid(row=2, column=1)

tk.Label(table, text="重量：").grid(row=3, column=0)
min_weight_entry = tk.Entry(table, width=3)
min_weight_entry.grid(row=3, column=1)
tk.Label(table, text="至").grid(row=3, column=2)
max_weight_entry = tk.Entry(table, width=3)
max_weight_entry.grid(row=3, column=3)
tk.Label(table, text="(克/个)").grid(row=3, column=4)

tk.Label(table, text="形状：").grid(row=4, column=0)
new_shape_entry = tk.Entry(table)
new_shape_entry.grid(row=4, column=1)

tk.Label(table, text="口感：").grid(row=5, column=0)
new_flavor_entry = tk.Entry(table)
new_flavor_entry.grid(row=5, column=1)

submit_button = tk.Button(questionnaire, text="回答完毕", command=new_submit)
submit_button.pack()
# 问卷卷默认隐藏
questionnaire.pack_forget()

# 运行主循环
root.mainloop()